import RPi.GPIO as GPIO
from playsound import playsound
import voicecomposer
import subprocess
import time
from datetime import datetime

#定义针脚
BtnPin = 7

#获取当前时间
calltime = datetime.now()

#设置针脚状态和检测回调
def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(BtnPin, GPIO.BOTH, callback=detect, bouncetime=200)

#显示按下按钮
def screen_print(x):
    if x == 0:
        print('  *******************')
        print('  * Button Pressed! *')
        print('  *******************')

def detect(chn):
    global calltime
    ticks = 2 #Defining the lowest interval seconds between twice speaking.
    screen_print(GPIO.input(BtnPin))
    interal = (datetime.now() - calltime).seconds

    #开关防抖
    if interal > ticks:
        #print(interal)
        speaking()
    else:
        pass
    calltime = datetime.now()

def speaking():
    
    #调用音频程序，生成MP3文件
    cmd = "python3 voicecomposer.py"
    
    #播放MP3文件
    playsound("demo.mp3")


def loop():
    while True:
        pass

#GPIO状态请零
def destroy():
    GPIO.cleanup()

#程序人口
if __name__ == '__main__':
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destroy()